package com.silong.util;

import org.apache.commons.lang.StringUtils;

import javax.servlet.http.Cookie;
import java.net.MalformedURLException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by kwj on 2016/07/13.
 */
public class CookieUtil {

    public static final String getCookieByName( Cookie[] cookies,String name){
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                if (c.getName().equals(name)) {
                    return c.getValue();
                }
            }
        }
        return  null;

    }

    public static final String getCookieAllString( Cookie[] cookies){
        String str ="";
        if (cookies != null && cookies.length > 0) {
            for (Cookie c : cookies) {
                str+= "key：" + c.getName() +"  value:"+c.getValue() +"/r/n";

            }
        }
        return  str;

    }

    public static String getTopDomainByUrl(String url) throws MalformedURLException {
        //String host = new URL(url).getHost().toLowerCase();// 此处获取值转换为小写
        Pattern pattern = Pattern.compile("[^\\.]+(\\.com\\.cn|\\.net\\.cn|\\.org\\.cn|\\.gov\\.cn|\\.com|\\.net|\\.cn|\\.org|\\.cc|\\.me|\\.tel|\\.mobi|\\.asia|\\.biz|\\.info|\\.name|\\.tv|\\.hk|\\.公司|\\.中国|\\.网络)");
        Matcher matcher = pattern.matcher(url);
        if (url.lastIndexOf("localhost")>-1)
        {
            return null;
        }
        if (matcher.find()) {
            return matcher.group();
        }else{
            url = url.replace("http://","");
            int i =url.indexOf("/");
            if (i>0)
            {
                url =url.substring(0,i);
            }

            return  url;
        }

    }



    public static Cookie getAddCookie( String name, String value,
                                   Integer expiry, String domain,String ctx) {
        Cookie cookie = new Cookie(name, value);
        if (expiry != null) {
            cookie.setMaxAge(expiry);
        }
        if (StringUtils.isNotBlank(domain)) {
            cookie.setDomain(domain);
        }
        cookie.setPath(StringUtils.isBlank(ctx) ? "/" : ctx);

        return cookie;
    }

    public static Cookie getAddCookie( String name, String value) {

        return  getAddCookie(  name,  value,
                null,null,null);
    }
    public static Cookie getAddCookie( String name, String value, Integer expiry) {

        return  getAddCookie(  name,  value,
                expiry, null, null);
    }
    public static Cookie getAddCookie( String name, String value, Integer expiry,String url) throws MalformedURLException {

        return  getAddCookie(  name,  value,
                expiry, getTopDomainByUrl(url), null);
    }


}
